<template>
  <div class="rebate-maintenance">
    <!-- 上部分：搜索区域 -->
    <div class="search-section">
      <el-form :model="searchForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="采购员">
              <el-input v-model="searchForm.planer" placeholder="请输入采购员" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="供应商ID">
              <el-input
                v-model="searchForm.supplierId"
                placeholder="双击选择供应商"
                @dblclick="openSupplierDialog"
                readonly
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="供应商名称">
              <el-input v-model="searchForm.supplierName" placeholder="请输入供应商名称" disabled />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="商品代码名称">
              <el-input v-model="searchForm.goodsOpcode" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="生产厂家">
              <el-input v-model="searchForm.manufacturer" placeholder="请输入生产厂家" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="ABC分类">
              <el-input v-model="searchForm.abc" placeholder="请输入分类" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="">
              <!-- <el-input v-model="searchForm.abc" placeholder="请输入分类" /> -->
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="">
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

    </div>

      <el-table
      :data="tableData"
      border
      style="width: 100%"
      :header-cell-style="{
        color: '#333',
        backgroundColor: '#eaf4ff',
        height: '20px'  // 表头固定高度
      }"
      :row-style="{ height: '20px' }"
      :cell-style="{ padding: '5px 0' }"
    >
        <el-table-column prop="venderCode" label="供应商代码" width="100" />
        <el-table-column prop="venderName" label="供应商名称" width="180" />
        <el-table-column prop="planer" label="采购员" width="80" />
        <el-table-column prop="comGoodsId" label="商品ID" width="80" />
        <el-table-column prop="goodsOpcode" label="商品代码" width="100" />
        <el-table-column prop="goodsName" label="商品名称" width="220" />
        <el-table-column prop="goodsDesc" label="商品规格" width="120" />
        <el-table-column prop="packageNum" label="包装数量" width="90" />
        <el-table-column prop="unitName" label="单位" width="60" />
        <el-table-column prop="defaultPrice" label="进价" width="80" />
        <el-table-column prop="purTaxRate" label="品种税率" width="100" />
        <el-table-column prop="lastPurInvoicePrice" label="上次发票价格" width="110" />
        <el-table-column
          prop="lastPurInvoiceDate"
          label="首营日期"
          width="100"
          :formatter="formatDate"
        />
        <el-table-column label="政策维护" width="90">
          <template #default="scope">
            <el-icon
              style="cursor: pointer; color: #409EFF; font-size: 25px;"
              @click="openPolicyDialog(scope.row)"
            >
              <Edit />
            </el-icon>
          </template>
        </el-table-column>

        <el-table-column prop="productLocation" label="上市许可持有人/生产厂家" width="200" />
        <el-table-column
          prop="createDate"
          label="首营日期"
          width="100"
          :formatter="formatDate"
        />

        <el-table-column prop="peyMethod" label="付款策略" width="100" />
        <el-table-column prop="peyDays" label="付款天数" width="90" />
        <el-table-column prop="abcType" label="ABC分类" width="90" />
        <el-table-column prop="marketCode" label="交易编码" width="120" />
      </el-table>

    <!-- 弹窗查询供应商 -->
    <el-dialog title="选择供应商" v-model="supplierDialogVisible" width="700px">
      <el-row :gutter="10" style="margin-bottom: 10px;">
        <el-col :span="16">
          <el-input
            v-model="supplierQuery"
            placeholder="请输入供应商名称"
            size="small"
          />
        </el-col>
        <el-col :span="1"/>
        <el-col :span="3">
          <el-button
            type="primary"
            size="small"
            style="width: 100%;"
            @click="searchSupplier">
            查询
          </el-button>
        </el-col>
        <el-col :span="2"/>
      </el-row>

      <el-table
        :data="supplierList"
        style="width: 100%;"
        @row-click="selectSupplier">
        <el-table-column prop="comPartyId" label="供应商ID" width="120" />
        <el-table-column prop="partyOpcode" label="供应商代码" />
        <el-table-column prop="partyName" label="供应商名称" />
      </el-table>
       <!-- 分页 -->
    <div style="margin-top: 10px; text-align: right;">
      <el-pagination
        v-model:current-page="dataVender.pageNum"
        v-model:page-size="dataVender.pageSize"
        :total="dataVender.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="searchSupplier"
        @current-change="searchSupplier"
      />
  </div>
    </el-dialog>
    <!-- 政策维护弹窗 -->
     <el-dialog v-model="policyDialogVisible" title="价格联系政策维护" width="1000" :before-close="handleClose">
    <el-form
      ref="policyFormRef"
      :model="policyForm"
      :rules="rules"
      label-width="100px"
      :inline="true"
    >
      <el-form-item label="生产厂家" prop="vender.productLocation">
        <el-input v-model="policyForm.vender.productLocation" disabled style="width: 240px"/>
      </el-form-item>

      <el-form-item label="商品ID" prop="comGoodsId">
        <el-input v-model="policyForm.comGoodsId" disabled style="width: 80px" />
      </el-form-item>

      <el-form-item label="商家信息" prop="vender.goodsInfo">
        <el-input v-model="policyForm.vender.goodsInfo" disabled style="width: 450px" />
      </el-form-item>

      <el-form-item label="供应商代码" prop="vender.venderCode">
        <el-input v-model="policyForm.vender.venderCode" disabled style="width: 100px" />
      </el-form-item>

      <el-form-item label="供应商名称" prop="vender.venderName">
        <el-input v-model="policyForm.vender.venderName" disabled style="width: 240px"/>
      </el-form-item>

      <el-form-item label="政策类型" prop="hnyyPurType">
        <el-select v-model="policyForm.hnyyPurType" placeholder="请选择政策类型" style="width: 150px">
          <el-option label="采购折让" value="1" />
          <el-option label="销售折让" value="2" />
          <el-option label="二次扣点" value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="取值来源" prop="hnyyPurRebateFromType">
        <el-select v-model="policyForm.hnyyPurRebateFromType" placeholder="请选择取值来源" style="width: 150px">
          <el-option label="销售流向" value="1" />
          <el-option label="购进流向" value="2" />
        </el-select>
      </el-form-item>

      <el-form-item label="协议起始期" prop="startDate">
        <el-date-picker v-model="policyForm.startDate" placeholder="请选择开始日期" type="date" style="width: 200px" />
      </el-form-item>

      <el-form-item label="协议结束期" prop="endDate">
        <el-date-picker v-model="policyForm.endDate" placeholder="请选择结束日期" type="date" style="width: 200px" />
      </el-form-item>

      <el-form-item label="折让计算期间" prop="hnyyRebateModueId" label-width="120px">
        <el-select v-model="policyForm.hnyyRebateModueId" placeholder="请选择折让计算期间" style="width: 140px">
          <el-option label="月度" value="1" />
          <el-option label="季度" value="2" />
          <el-option label="半年度" value="3" />
          <el-option label="年度" value="4" />
        </el-select>
      </el-form-item>

      <el-form-item label="折让方式" prop="hnyyRebateMethdId">
        <el-select v-model="policyForm.hnyyRebateMethdId" placeholder="请选择折让方式" style="width: 160px">
          <el-option label="票扣" value="1" />
          <el-option label="红票" value="2" />
          <el-option label="现金" value="3" />
        </el-select>
      </el-form-item>

      <el-form-item label="采购折让类型" prop="hnyyRebateTypeId" label-width="120px">
        <el-select v-model="policyForm.hnyyRebateTypeId" placeholder="请选择采购折让类型" style="width: 160px">
          <el-option label="付款折让" value="1" />
          <el-option label="已销定返" value="2" />
          <el-option label="总量折让" value="3" />
          <el-option label="税率补偿" value="4" />
          <el-option label="扫码补偿" value="5" />
        </el-select>
      </el-form-item>

      <el-form-item label="中标价" prop="zbPrice">
        <el-input v-model="policyForm.zbPrice" style="width: 100px"/>
      </el-form-item>

      <el-form-item label="进价" prop="purPrice">
        <el-input v-model="policyForm.purPrice" style="width: 100px"/>
      </el-form-item>

      <el-form-item label="品种税率" prop="goodsRate">
        <el-select v-model="policyForm.goodsRate" placeholder="请选择品种税率" style="width: 150px">
          <el-option label="0.00" value="0.00" />
          <el-option label="0.01" value="0.01" />
          <el-option label="0.03" value="0.03" />
          <el-option label="0.06" value="0.06" />
          <el-option label="0.09" value="0.09" />
          <el-option label="0.13" value="0.13" />
          <el-option label="0.16" value="0.16" />
        </el-select>
      </el-form-item>

      <el-form-item label="客户代码" prop="clientId">
        <el-input
          v-model="policyForm.clientId"
          placeholder="双击选择客户"
          :disabled="!!policyForm.sysClientPriceSetsList"
          @dblclick="openClientDialog"
          readonly
          style="width:200px"
        />
        <el-button type="text" style="margin-left: 10px;" @click="resetClientCode" >重置</el-button>
      </el-form-item>

      <el-form-item label="客户名称" prop="clientName">
        <el-input v-model="policyForm.clientName" placeholder="客户名称" disabled style="width: 200px"/>
      </el-form-item>

      <el-form-item label="客户集合" prop="sysClientPriceSetsList">
        <el-input
          v-model="policyForm.sysClientPriceSetsList"
          placeholder="双击选择客户集合"
          style="width: 460px"
          @dblclick="clientSetDialogVisible = true"
          :disabled="!!policyForm.clientName"
        />
        <el-button type="text" style="margin-left: 10px;" @click="resetClientCodeList" >重置</el-button>
      </el-form-item>

      <el-form-item label="采购折让比率" prop="purRate">
        <el-input
          v-model="policyForm.purRate"
          placeholder="保留两位小数"
          style="width: 120px"
          :disabled="!!policyForm.purRebatePrice"
        />
      </el-form-item>

      <el-form-item label="采购折让单价" prop="purRebatePrice">
        <el-input
          v-model="policyForm.purRebatePrice"
          placeholder="请输入整数"
          style="width: 120px"
          :disabled="!!policyForm.purRate"
        />
      </el-form-item>

      <el-form-item label="付款账期（天数）" label-width="180px" prop="payDay">
        <el-input v-model="policyForm.payDay" placeholder="请输入整数" style="width: 120px"/>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="policyDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="savePolicy">保存</el-button>
    </template>
  </el-dialog>
     <!-- 弹窗查询客户 -->
    <el-dialog title="选择客户" v-model="clientDialogVisible" width="700px">
      <el-row :gutter="10" style="margin-bottom: 10px;">
        <el-col :span="16">
          <el-input
            v-model="clientQuery"
            placeholder="请输入客户名称"
            size="small"
          />
        </el-col>
        <el-col :span="1"/>
        <el-col :span="3">
          <el-button
            type="primary"
            size="small"
            style="width: 100%;"
            @click="clientSearch">
            查询
          </el-button>
        </el-col>
        <el-col :span="2"/>
      </el-row>

      <el-table
        :data="clientList"
        style="width: 100%;"
        @row-click="selectClient">
        <el-table-column prop="comPartyId" label="客户ID" width="120" />
        <el-table-column prop="partyOpcode" label="客户代码" />
        <el-table-column prop="partyName" label="客户名称" />
      </el-table>
       <!-- 分页 -->
      <div style="margin-top: 10px; text-align: right;">
        <el-pagination
          v-model:current-page="dataClient.pageNum"
          v-model:page-size="dataClient.pageSize"
          :total="dataClient.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="clientSearch"
          @current-change="clientSearch"
        />
      </div>
    </el-dialog>

    <!-- 弹窗查询客户集合 -->
    <el-dialog title="选择客户集合" v-model="clientSetDialogVisible" width="700px">
      <el-row :gutter="10" style="margin-bottom: 10px;">
        <el-col :span="16">
          <el-input
            v-model="clientSetQuery"
            placeholder="请输入客户集合名称"
            size="small"
          />
        </el-col>
        <el-col :span="1"/>
        <el-col :span="3">
          <el-button
            type="primary"
            size="small"
            style="width: 100%;"
            @click="clientSetSearch">
            查询
          </el-button>
        </el-col>
        <el-col :span="2"/>
      </el-row>

      <el-table
        :data="clientSetList"
        style="width: 100%;"
        @selection-change="handleClientSetSelection"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="sysClientPriceSetsId" label="客户代码" width="120" />
        <el-table-column prop="priceSetName" label="客户名称" />
      </el-table>

      <div style="margin-top: 10px;">
        <span>暂存的客户集合：</span>
        <el-tag
          v-for="item in tempSelectedClientSets"
          :key="item.sysClientPriceSetsId"
          closable
          @close="removeTemp(item)"
          style="margin-right: 5px;"
        >
          {{ item.sysClientPriceSetsId }}/{{ item.priceSetName }}
        </el-tag>
      </div>

      <template #footer>
        <el-button @click="clientSetDialogVisible = false">取消</el-button>
        <el-button @click="saveTemp">暂存</el-button>
        <el-button type="primary" @click="confirmClientSet">确认</el-button>
      </template>
      <!-- 分页 -->
      <div style="margin-top: 10px; text-align: right;">
        <el-pagination
          v-model:current-page="dataClientSet.pageNum"
          v-model:page-size="dataClientSet.pageSize"
          :total="dataClientSet.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="clientSetSearch"
          @current-change="clientSetSearch"
        />
      </div>
    </el-dialog>
  </div>
  <div class="card">
      <el-pagination
          v-model:current-page="searchForm.pageNum"
          v-model:page-size="searchForm.pageSize"
          layout="total,sizes, prev, pager, next"
          :total="searchForm.total"
          :page-sizes="[20, 40, 80]"
          @current-change="handleSearch"
          @size-change="handleSearch"
      />
    </div>
</template>

<script setup>
import { reactive, ref,nextTick } from 'vue'
import request from '@/utils/request';
import { ElMessage } from 'element-plus';
import dayjs from "dayjs";
import { Edit } from '@element-plus/icons-vue'
import { ElLoading } from 'element-plus';

let loadingInstance = null;
// 供应商查询分页查询参数
const dataVender = ref({
  pageNum: 1,
  pageSize: 20,
  total:0
})

// 客户查询分页参数
const dataClient = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0
})

// 客户集合查询分页参数
const dataClientSet = ref({
  pageNum: 1,
  pageSize: 20,
  total: 0
})

// 搜索表单数据
const searchForm = ref({
  planer: '',
  supplierId: '',
  supplierName: '',
  goodsOpcode: '',
  manufacturer: '',
  abc: '',
  pageNum: 1,
  pageSize: 20,
  total: 0
})
// 政策维护数据
let policyForm=reactive({
  hnyyPurRebateListId: '',
  hnyyPurType: '',
  hnyyPurRebateFromType: '',
  venderId: '',
  startDate: '',
  endDate: '',
  hnyyRebateModueId: '',
  hnyyRebateMethdId:'',
  hnyyRebateTypeId:'',
  comGoodsId:'',
  goodsRate:'',
  zbPrice:'',
  purPrice:'',
  clientId:'',
  sysClientPriceSetsList:'',
  purRate:'',
  purRebatePrice:'',
  payDay:'',
  opFlag:'0',
  creater:'',
  createDate:'',
  checker:'',
  checkDate:'',
  vender:{
    venderName:'',
    goodsInfo:'',
    venderCode:'',
    productLocation:''
  }
})
// 政策维护对话框
const policyDialogVisible = ref(false)
// 客户筛选对话框
const clientDialogVisible = ref(false)
const clientQuery = ref('')
const clientList = ref([])
const openClientDialog=()=>{
  clientDialogVisible.value = true
}
// 表单校验
const validateSysOrClient = (rule, value, callback) => {
  console.log('policyForm.hnyyPurRebateFromType',policyForm.hnyyPurRebateFromType)
  if (policyForm.hnyyPurRebateFromType === '1') {
    if (!policyForm.sysClientPriceSetsList && !policyForm.clientId) {
      return callback(new Error('价格集和客户ID至少选择一个'))
    }
  }else{
    console.log('policyForm.clientId',policyForm.clientId)
    callback()
  }
  callback()
}
const policyFormRef = ref()
const rules = {
  hnyyPurType: [{ required: true, message: "请选择政策类型", trigger: "change" }],
  hnyyPurRebateFromType: [{ required: true, message: "请选择取值来源", trigger: "change" }],
  startDate: [{ required: true, message: "请选择开始日期", trigger: "change" }],
  endDate: [{ required: true, message: "请选择结束日期", trigger: "change" }],
  hnyyRebateModueId: [{ required: true, message: "请选择折让计算期间", trigger: "change" }],
  hnyyRebateMethdId: [{ required: true, message: "请选择折让方式", trigger: "change" }],
  hnyyRebateTypeId: [{ required: true, message: "请选择采购折让类型", trigger: "change" }],
  zbPrice: [{ required: true, message: "请输入中标价", trigger: "blur" }],
  purPrice: [{ required: true, message: "请输入进价", trigger: "blur" }],
  goodsRate: [{ required: true, message: "请选择品种税率", trigger: "change" }],
  clientId: [{ required: true, message: "请输入客户代码或选择客户集合", trigger: "blur" }],
  sysClientPriceSetsList: [{ validator: validateSysOrClient, trigger: 'blur' }],
  clientId: [{ validator: validateSysOrClient, trigger: 'blur' }],
  // 二选一
  purRate: [
    { validator: (rule, value, callback) => {
        if (!value && !policyForm.purRebatePrice) {
          callback(new Error("折让比率和折让单价必须填写一个"))
        } else {
          callback()
        }
      }, trigger: "blur"
    }
  ],
  purRebatePrice: [
    { validator: (rule, value, callback) => {
        if (!value && !policyForm.purRate) {
          callback(new Error("折让比率和折让单价必须填写一个"))
        } else {
          callback()
        }
      }, trigger: "blur"
    }
  ],
  payDay: [
    { required: true, message: "请输入付款账期", trigger: "blur" },
    { validator: (rule, value, callback) => {
        if (!/^\d+$/.test(value)) {
          callback(new Error("付款账期必须为整数"))
        } else {
          callback()
        }
      }, trigger: "blur"
    }
  ]
}

const selectClient = (row) => {
  // 回填客户信息
  policyForm.clientId = row.comPartyId
  policyForm.clientName = row.partyName

  // 关闭客户选择对话框
  clientDialogVisible.value = false
}
const resetClientCode=()=>{
  policyForm.clientId = ''
  policyForm.clientName = ''
}
const resetClientCodeList=()=>{
  policyForm.sysClientPriceSetsList = ''
  policyForm.clientName = ''
  sysClientPriceSetsListId.value = ''
}
const clientSearch = () => {
  if (!clientQuery.value) return ElMessage.warning('请输入客户名称')
  nextTick(() => {
    loadingInstance = ElLoading.service({
      target: '.el-dialog__body',
      text: '加载中...'
    });
  });
  request.get('/link/getClient', { params: { name: clientQuery.value ,pageNum:dataClient.value.pageNum,pageSize:dataClient.value.pageSize} }).then((res) => {
    console.log('res=======> ', res)
    if (res.code === 200) {
      clientList.value = res.data.list
      dataClient.value.total = res.data.total
    }
  }).catch((err) => {
      ElMessage.error('详情加载失败');
      console.error(err);
    }).finally(() => {
      if (loadingInstance) loadingInstance.close();
    });
}

const openPolicyDialog = async (row) => {
  // 打开政策维护对话框
  policyDialogVisible.value = true
  console.log('row', row)
  try {
    // 等待 getPolicy 请求完成
    // const res = await request.get('/link/getPolicy', {
    //   params: {
    //     comGoodsId: row.comGoodsId,
    //     sysVenderGoodsRefId: row.sysVenderGoodsRefId
    //   }
    // });
    // console.log('res=======>1211 ', res)
    // if (res.code === 200) {
    //   Object.assign(policyForm, res.data)
    // }
    // console.log('policyForm.sysClientPriceSetsList', policyForm.sysClientPriceSetsList)
    // if (policyForm.sysClientPriceSetsList) {
    //   sysClientPriceSetsListId.value = policyForm.sysClientPriceSetsList
    //   // 等待 getSysClientPriceSets 请求完成
    //   const res2 = await request.get('/link/getSysClientPriceSets', {
    //     params: { sysClientPriceSetsList: policyForm.sysClientPriceSetsList }
    //   });
    //   console.log('res====>121', res2)
    //   if (res2.code === 200) {
    //     policyForm.sysClientPriceSetsList = res2.data
    //   }
    // }
    policyForm.vender.productLocation = row.productLocation
    policyForm.vender.venderName = row.venderName
    policyForm.vender.goodsInfo = `${row.goodsOpcode} / ${row.goodsName} / ${row.goodsDesc} / ${row.unitName}`
    policyForm.vender.venderCode = row.venderCode
    policyForm.zbPrice = row.defaultPrice
    policyForm.purPrice = row.defaultPrice
    policyForm.venderId = row.venderPartyId
    policyForm.comGoodsId = row.comGoodsId

  } catch (error) {
    console.error('请求失败', error)
  }
}

// 客户集合
const clientSetQuery=ref('')
const clientSetList=ref([])
const clientSetDialogVisible=ref(false)
const clientSetSearch=()=>{
  if (!clientSetQuery.value) return ElMessage.warning('请输入客户集合名称')

  request.get('/link/getClientList', { params: { name: clientSetQuery.value ,pageNum:dataClientSet.value.pageNum,pageSize:dataClientSet.value.pageSize} }).then((res) => {
    console.log('res=======> ', res)
    if (res.code === 200) {
      clientSetList.value = res.data.list
      dataClientSet.value.total = res.data.total
    }
  }).catch((err) => {
    ElMessage.error('详情加载失败');
    console.error(err);
  }).finally(() => {
    if (loadingInstance) loadingInstance.close();
  });
}
// 存放当页选中的客户集合
const selectedClientSets = ref([])
// 暂存的客户集合
const tempSelectedClientSets = ref([])
// 监听多选
const handleClientSetSelection = (val) => {
  selectedClientSets.value = val
}
// 暂存按钮
const saveTemp = () => {
  // 合并到暂存区，避免重复
  const ids = tempSelectedClientSets.value.map(i => i.sysClientPriceSetsId)
  selectedClientSets.value.forEach(item => {
    if (!ids.includes(item.sysClientPriceSetsId)) {
      tempSelectedClientSets.value.push(item)
    }
  })
  // 清空本页选择
  selectedClientSets.value = []
  ElMessage.success('已暂存所选客户集合，可以继续查询')
}
// 移除单个暂存
const removeTemp = (item) => {
  tempSelectedClientSets.value = tempSelectedClientSets.value.filter(i => i.sysClientPriceSetsId !== item.sysClientPriceSetsId)
}

const sysClientPriceSetsListId=ref('')
// 点击确认
const confirmClientSet = () => {
  policyForm.sysClientPriceSetsList = tempSelectedClientSets.value
    .map(item => `${item.priceSetName}`)
    .join(',');

  sysClientPriceSetsListId.value = tempSelectedClientSets.value
    .map(item => item.sysClientPriceSetsId)
    .join(',');

  clientSetDialogVisible.value = false
}


const handleClose=()=>{
  policyDialogVisible.value = false
   policyForm = Object.assign(policyForm, {
        hnyyPurRebateListId: '',
        hnyyPurType: '',
        hnyyPurRebateFromType: '',
        venderId: '',
        startDate: '',
        endDate: '',
        hnyyRebateModueId: '',
        hnyyRebateMethdId: '',
        hnyyRebateTypeId: '',
        comGoodsId: '',
        goodsRate: '',
        zbPrice: '',
        purPrice: '',
        clientId: '',
        sysClientPriceSetsList: '',
        purRate: '',
        purRebatePrice: '',
        payDay: '',
        opFlag: 'NEW',
        creater: '',
        createDate: '',
        checker: '',
        checkDate: '',
        vender: {
          venderName: '',
          goodsInfo: '',
          venderCode: '',
          productLocation: ''
        }
      })
}

// 表格数据
const tableData = ref([])

// 弹窗显示状态
const supplierDialogVisible = ref(false)
// 弹窗查询关键字
const supplierQuery = ref('')
// 查询到的供应商列表
const supplierList = ref([])

// 打开供应商弹窗
const openSupplierDialog = () => {
  supplierDialogVisible.value = true
}


const formatDate = (row, column) => {
  const date = row[column.property]
  return date ? dayjs(date).format('YYYY-MM-DD') : ''
}

// 查询供应商
const searchSupplier = () => {
  if(!supplierQuery.value)
  return ElMessage.warning('请输入供应商名称')
 nextTick(() => {
    loadingInstance = ElLoading.service({
      target: '.el-dialog__body', // 👈 重点，挂载在 el-dialog 内容区
      text: '加载中...'
    });
  });
  request.get('/link/getParty', {params: { name: supplierQuery.value ,pageNum:dataVender.value.pageNum,pageSize:dataVender.value.pageSize} }).then((res)=>{
    console.log('res=======> ',res)
    if(res.code === 200){
      supplierList.value = res.data.list
      dataVender.value.total = res.data.total
    }
  })
  .catch((err) => {
    console.error('请求失败', err);
  }).finally(() => {
    if (loadingInstance) loadingInstance.close();
  });
}

// 点击供应商列表选择
const selectSupplier = (row) => {
  searchForm.value.supplierId = row.comPartyId
  searchForm.value.supplierName = row.partyName
  supplierDialogVisible.value = false
}

// 查询按钮
const handleSearch = () => {
  if (!searchForm.value.supplierName) {
    return ElMessage.warning('请输入搜索条件')
  }

  // 开启 loading 遮罩
  const loading = ElLoading.service({
    lock: true,
    text: '正在查询，请稍候...',
    background:'rgba(255, 255, 255, 0.7)',
  })

  request.post('/link/getGoods', searchForm.value)
    .then((res) => {
      console.log('res=======> ', res)
      if (res.code === 200) {
        tableData.value = res.data.list
        searchForm.value.pageNum = res.data.pageNum
        searchForm.value.pageSize = res.data.pageSize
        searchForm.value.total = res.data.total
        if (res.data.length === 0) {
          ElMessage.info('未找到相关数据')
        }
      } else {
        ElMessage.error(res.msg || '获取数据失败')
      }
    })
    .catch(() => {
      ElMessage.error('请求出错，请稍后重试')
    })
    .finally(() => {
      // 关闭遮罩层
      loading.close()
    })
}

// 重置按钮
const resetForm = () => {
  searchForm.value = {
    planer: '',
    supplierId: '',
    supplierName: '',
    goodsOpcode: '',
    manufacturer: '',
    abc: ''
  }
  tableData.value = []
}

// 保存或更新政策
const savePolicy = () => {
  console.log('policyForm', policyForm)

  policyFormRef.value.validate((valid) => {
    if (!valid) return

    policyForm.sysClientPriceSetsList = sysClientPriceSetsListId.value

    // 判断是新增还是更新
    const isUpdate = !!policyForm.hnyyPurRebateListId
    // const url = isUpdate ? '/link/updatePolicy' : '/link/addPolicy'
    const url ='/link/addPolicy'
    const successMsg = isUpdate ? '更新成功' : '保存成功'
    const errorMsg = isUpdate ? '更新失败' : '保存失败'

    request.post(url, policyForm).then((res) => {
      if (res.code === 200) {
        console.log('res', res)
        ElMessage.success(successMsg)
      } else {
        ElMessage.error(res.msg || errorMsg)
      }
    })

    // 关闭对话框
    policyDialogVisible.value = false

    // 重置表单
    Object.assign(policyForm, {
      hnyyPurRebateListId: '',
      hnyyPurType: '',
      hnyyPurRebateFromType: '',
      venderId: '',
      startDate: '',
      endDate: '',
      hnyyRebateModueId: '',
      hnyyRebateMethdId: '',
      hnyyRebateTypeId: '',
      comGoodsId: '',
      goodsRate: '',
      zbPrice: '',
      purPrice: '',
      clientId: '',
      sysClientPriceSetsList: '',
      purRate: '',
      purRebatePrice: '',
      payDay: '',
      opFlag: '0',
      creater: '',
      createDate: '',
      checker: '',
      checkDate: '',
      vender: {
        venderName: '',
        goodsInfo: '',
        venderCode: '',
        productLocation: ''
      }
    })
  })
}

</script>

<style scoped>
.rebate-maintenance {
  padding: 20px;
}
.search-section {
  margin-bottom: 20px;
  background: #f8f8f8;
  padding: 15px;
  border-radius: 5px;
}
.table-section {
  background: #fff;
  padding: 15px;
  border-radius: 5px;
}

.btn-group {
  text-align: right;
  padding-top: 10px;
}

</style>
